package com.offics.loan.infrastructure.persistence;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offics.loan.domain.entity.Loan;
import com.offics.loan.domain.repository.LoanRepository;
import com.offics.loan.infrastructure.persistence.mapper.LoanMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 * 贷款仓储实现类
 */
@Repository
@RequiredArgsConstructor
public class LoanRepositoryImpl extends ServiceImpl<LoanMapper, Loan> implements LoanRepository {

    private final LoanMapper loanMapper;

    @Override
    public Optional<Loan> findById(Long id) {
        return Optional.ofNullable(loanMapper.selectById(id));
    }

    @Override
    public Optional<Loan> findByLoanNo(String loanNo) {
        LambdaQueryWrapper<Loan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Loan::getLoanNo, loanNo);
        return Optional.ofNullable(loanMapper.selectOne(wrapper));
    }

    @Override
    public List<Loan> findByUserId(Long userId) {
        LambdaQueryWrapper<Loan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Loan::getUserId, userId);
        wrapper.orderByDesc(Loan::getCreateTime);
        return loanMapper.selectList(wrapper);
    }

    @Override
    public List<Loan> findByUserIdAndStatus(Long userId, Integer status) {
        LambdaQueryWrapper<Loan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Loan::getUserId, userId);
        wrapper.eq(Loan::getStatus, status);
        wrapper.orderByDesc(Loan::getCreateTime);
        return loanMapper.selectList(wrapper);
    }

    @Override
    public IPage<Loan> findPage(IPage<Loan> page, Long userId, Integer status) {
        LambdaQueryWrapper<Loan> wrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            wrapper.eq(Loan::getUserId, userId);
        }
        if (status != null) {
            wrapper.eq(Loan::getStatus, status);
        }
        wrapper.orderByDesc(Loan::getCreateTime);
        return loanMapper.selectPage(page, wrapper);
    }

    @Override
    public boolean save(Loan loan) {
        return loanMapper.insert(loan) > 0;
    }

    @Override
    public Loan saveAndReturn(Loan loan) {
        if (save(loan)) {
            return loan;
        }
        return null;
    }

    @Override
    public boolean update(Loan loan) {
        return loanMapper.updateById(loan) > 0;
    }

    @Override
    public boolean deleteById(Long id) {
        return loanMapper.deleteById(id) > 0;
    }

    @Override
    public boolean deleteByUserId(Long userId) {
        LambdaQueryWrapper<Loan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Loan::getUserId, userId);
        return loanMapper.delete(wrapper) > 0;
    }

    @Override
    public String generateLoanNo() {
        // 生成贷款编号：LOAN + 年月日时分秒 + 4位随机数
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        return "LOAN" + dateTime + randomNum;
    }

    @Override
    public boolean existsByLoanNo(String loanNo) {
        LambdaQueryWrapper<Loan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Loan::getLoanNo, loanNo);
        return loanMapper.selectCount(wrapper) > 0;
    }
}
